package cn.xxy.datasource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.xxy.beans.DataSourceConfig;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Map;
import java.util.logging.Logger;

public class NoneDataSourceAdapter extends DataSourceAdapter implements DataSource {
	private static Log log = LogFactory.getLog(NoneDataSourceAdapter.class);
	PrintWriter wout;
	private DataSourceConfig dataSourceConfig;

	@Override
	protected DataSource adapter(DataSourceConfig config) {
		this.dataSourceConfig = config;
		try {
			Class.forName(config.getDriverClass());
			injectProperty(this, config);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
		return this;
	}

	@Override
	protected DataSource adapter(Map<String, String> mapConfig) {
		DataSourceConfig config = new DataSourceConfig();
		injectProperty(config, mapConfig);
		return adapter(config);
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return wout;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {wout=out;}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {}

	@Override
	public int getLoginTimeout() throws SQLException {
		return 0;
	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return Logger.getLogger(NoneDataSourceAdapter.class.getName());
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return false;
	}

	@Override
	public Connection getConnection() throws SQLException {
		return getConnection(dataSourceConfig.getUsername(), dataSourceConfig.getPassword());
	}

	@Override
	public final synchronized Connection getConnection(String username, String password) throws SQLException {
		return DriverManager.getConnection(dataSourceConfig.getJdbcUrl(), username, password);
	}
}
